package com.ruangong.GitClient.app.TravelExpense;

import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.ruangong.GitClient.R;

import java.util.ArrayList;

public class TravelEventsListActivity extends AppCompatActivity {
    private ListView listViewEvents;
    private ArrayList<TravelEvent> travelEvents;
    private TravelEventsListAdapter adapter;
    private TextView textViewTitle;
    private FloatingActionButton addButton;
    private static final int ADD_TRAVEL_EVENT_REQUEST = 1;

    // 声明数据库帮助类和数据库实例
    private TravelDBHelper dbHelper;
    private SQLiteDatabase db;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_travelevents);

        // 初始化视图
        textViewTitle = findViewById(R.id.textViewTitle);
        listViewEvents = findViewById(R.id.listViewEvents);
        addButton = findViewById(R.id.addButton);

        // 设置标题
        textViewTitle.setText("旅游事件列表");

        // 初始化数据库帮助类和数据库实例
        dbHelper = new TravelDBHelper(this);
        db = dbHelper.getWritableDatabase();

        // 初始化旅行事件数据
        travelEvents = getTravelEvents();

        // 初始化适配器
        adapter = new TravelEventsListAdapter(this, travelEvents);

        // 关联适配器与 ListView
        listViewEvents.setAdapter(adapter);

        // ListView点击事件，处理点击旅行事件条目的逻辑
        listViewEvents.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                // 获取被点击的旅行事件条目
                TravelEvent clickedEvent = travelEvents.get(position);

                // 获取被点击事件的ID
                int eventId = clickedEvent.getId();

                // 创建一个意图，启动旅行事件详情页面，并将事件详情传递过去
                Intent intent = new Intent(TravelEventsListActivity.this, TravelEventDetailsActivity.class);
                intent.putExtra("TRAVEL_EVENT", clickedEvent);
                intent.putExtra("EVENT_ID", eventId);
                startActivity(intent);
            }
        });

        addButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivityForResult(new Intent(TravelEventsListActivity.this, AddTravelActivity.class), ADD_TRAVEL_EVENT_REQUEST);
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 关闭数据库连接
        if (db != null) {
            db.close();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.d("TravelEventsListActivity", "onActivityResult: requestCode=" + requestCode + ", resultCode=" + resultCode);
        if (requestCode == ADD_TRAVEL_EVENT_REQUEST && resultCode == RESULT_OK) {
            if (data != null && data.hasExtra("eventName") && data.hasExtra("numberOfPeople")) {
                //int eventId=data.getIntExtra("eventId");
                String eventName = data.getStringExtra("eventName");
                int numberOfPeople = data.getIntExtra("numberOfPeople", 0);
                Log.d("TravelEventsListActivity", "onActivityResult: eventName=" + eventName + ", numberOfPeople=" + numberOfPeople);
                // 将新的旅行事件添加到数据库
                addTravelEventToDatabase(eventName, numberOfPeople);

                // 更新列表
                updateTravelEventList();
            }
        }

    }

    @Override
    protected void onResume() {
        super.onResume();
        // 在活动恢复时更新旅行事件列表
        updateTravelEventList();
    }

    // 获取旅行事件数据
    private ArrayList<TravelEvent> getTravelEvents() {
        ArrayList<TravelEvent> events = new ArrayList<>();
        // 查询数据库获取旅行事件数据
        Cursor cursor = db.query(TravelDBHelper.TABLE_EVENTS, null, null, null, null, null, null);
        if (cursor != null && cursor.moveToFirst()) {
            do {
                @SuppressLint("Range") int eventId=cursor.getInt(cursor.getColumnIndex(TravelDBHelper.COLUMN_ID));
                @SuppressLint("Range") String eventName = cursor.getString(cursor.getColumnIndex(TravelDBHelper.COLUMN_EVENT_NAME));
                @SuppressLint("Range") int numberOfPeople = cursor.getInt(cursor.getColumnIndex(TravelDBHelper.COLUMN_NUMBER_OF_PEOPLE));
                events.add(new TravelEvent(eventId,eventName, numberOfPeople));
            } while (cursor.moveToNext());
            cursor.close();
        }
        return events;
    }

    // 添加新的旅行事件到数据库
    private void addTravelEventToDatabase(String eventName, int numberOfPeople) {
        ContentValues values = new ContentValues();
        //values.put(TravelDBHelper.COLUMN_ID,eventId);
        values.put(TravelDBHelper.COLUMN_EVENT_NAME, eventName);
        values.put(TravelDBHelper.COLUMN_NUMBER_OF_PEOPLE, numberOfPeople);
        long newRowId = db.insert(TravelDBHelper.TABLE_EVENTS, null, values);
        if (newRowId != -1) {
            Log.d("Database", "New event inserted successfully, row ID: " + newRowId);
        } else {
            Log.e("Database", "Failed to insert new event into the database");
        }
        Log.d("Database", "Inserted row ID: " + newRowId); // 添加这行来输出 newRowId 的值
    }

    // 更新旅行事件列表
    private void updateTravelEventList() {
        travelEvents.clear();
        travelEvents.addAll(getTravelEvents());
        adapter.notifyDataSetChanged();
    }
}







